<template>
    <div class="audio-player">
        <div class="tabs">
            <button class="active">初中英语</button>
            <button>中考真题</button>
            <button>高中英语</button>
            <button>高考真题</button>
            <button>CET4</button>
            <button>CET6</button>
        </div>
        <div class="audio-control">
            <h3 class="title">标题：七年级-第一单元测试-错题集合</h3>
            <button class="return-button" @click="back">返回</button>
            <!-- 添加返回按钮 -->
            <div class="audio-progress">
                <span class="time">00:00</span>
                <input type="range" min="0" max="1350" value="0" step="1" class="progress-bar"
                    @input="updateCurrentTime" @change="seekToTime" />
                <span class="time">23:50</span>
                <div class="anchors">
                    <div v-for="(anchor, index) in anchors" :key="index" class="anchor" :style="{ left: `${anchor}%` }">
                        <div class="anchor-arrow">
                            <span class="anchor-number">{{ getAnchorLabel(index) }}</span>
                        </div>
                        <div class="anchor-line"></div>
                    </div>
                </div>
            </div>
            <div class="playback-controls">
                <p>播放控制区：</p>
                <el-button type="primary" @click="handleStartPlayer">
                    开始播放
                </el-button>
                <el-button type="primary" @click="handleStopPlayer">
                    停止播放
                </el-button>
                <el-button type="primary" @click="handleSetSpeed">
                    局部播放速度设置
                </el-button>
                <el-button type="primary" @click="handleStartCheckPlay">
                    根据选中错题播放
                </el-button>
                <el-button type="primary" @click="handleStartToEndPlay">
                    从头播放
                </el-button>
            </div>
            <div class="audio-anchors">
                <div>
                    <p>错题列表：</p>
                </div>
                <div class="anchor-checkboxes">
                    <!-- <label
            v-for="(anchor, index) in anchors"
            :key="index"
            v-if="index % 2 === 0"
          >
            <input
              type="checkbox"
              :id="'anchor-' + index"
              :value="index"
              v-model="selectedAnchors"
              @change="toggleAnchor(index)"
            />
            {{ Math.floor(index / 2) + 1 }}
          </label> -->
                    <label v-for="(question, index) in questions" :key="index">
                        <input type="checkbox" :id="'anchor-' + index" :value="index" v-model="selectedAnchors"
                            @change="toggleAnchor(index)" />
                        {{ extractQuestionNumber(question.questionName) }}
                    </label>
                </div>
            </div>
        </div>
        <div class="text-content">
            <div>
                <p>原文：</p>
            </div>
            <div class="text-original">
                <p>
                    <span v-for="(word, index) in originalText" :key="index"
                        :class="{ highlighted: highlightedText.includes(index) }">{{ word }}</span>
                </p>
            </div>
            <div>
                <p>译文：</p>
            </div>
            <div class="text-translation">
                <p>
                    <span v-for="(word, index) in translationText" :key="index" :class="{
                        highlighted: highlightedText.includes(
                            index + originalText.length
                        ),
                    }">{{ word }}</span>
                </p>
            </div>
        </div>
        <div class="questions">
            <div v-for="(question, index) in questions" :key="index">
                <p>{{ question.questionName }}</p>
                <p>{{ question.question }}</p>
                <p>{{ question.questionAnswer }}</p>
                <p>
                    正确答案：{{ question.correctAnswer }},易错答案：{{
                        question.wrongAnswer
                    }}
                </p>
                <p>名师备注：{{ question.note }}</p>
                <hr v-if="index < questions.length - 1" />
            </div>
        </div>
        <SetLocalPlayerSpeed v-if="isShowSpeedSettingFlag" :isVisible="isShowSpeedSettingFlag" :initialSpeed="speed"
            @speed-set="handleSpeedSet" @update:isVisible="isShowSpeedSettingFlag = $event" />
    </div>
</template>

<script>
import SetLocalPlayerSpeed from "./setLocalPlayerSpeed.vue";
export default {
    components: {
        SetLocalPlayerSpeed, //导入设置局部组件
    },
    props: {
        initialSpeed: {
            type: Number,
            default: 1.0,
        },
    },
    data() {
        return {
            currentTime: 0,
            anchors: [20, 50, 60, 90], // Anchor times in seconds
            anchorNames: ["1-s", "1-e", "2-s", "2-e"],
            highlightedText: [],
            selectedAnchors: [], // Selected anchors
            originalText: [
                "The",
                "recent",
                "high-profile",
                "movie",
                "Crazy",
                "Rich",
                "Asians",
                "shows",
                "a",
                "side",
                "of",
                "Singapore",
                "that",
                "most",
                "people",
                "-not",
                "even",
                "Singaporeans",
                "don't",
                "get",
                "to",
                "see.",
                "While",
                "the",
                "story",
                "is",
                "largely",
                "set",
                "in",
                "Singapore,",
                "filming",
                "took",
                "place",
                "both",
                "in",
                "the",
                "city",
                "state",
                "and",
                "neighbouring",
                "Malaysia.",
                "Attractions",
                "such",
                "as",
                "Singapore's",
                "Marina",
                "Bay",
                "Sands",
                "and",
                "Malaysia's",
                "heritage",
                "Cheong",
                "Fatt",
                "Sze",
                "Mansion",
                "appeal",
                "to",
                "people.",
            ],
            translationText: [
                "最近",
                "备受",
                "瞩目",
                "的电影",
                "《",
                "疯狂的",
                "亚洲",
                "富人",
                "》",
                "展示",
                "了",
                "大多",
                "数",
                "人",
                "（",
                "甚至",
                "新加坡",
                "人",
                "）",
                "都",
                "不",
                "熟悉",
                "的",
                "新加坡",
                "生活",
                "。",
                "虽然",
                "故事",
                "主要",
                "发生",
                "在",
                "新加坡",
                "，",
                "但",
                "拍摄",
                "地点",
                "包括",
                "新加坡",
                "和",
                "邻近",
                "的",
                "马来西亚",
                "。",
                "像",
                "新加坡",
                "的",
                "滨海",
                "湾",
                "金沙",
                "和",
                "马来西亚",
                "的",
                "文化遗产",
                "陈",
                "氏",
                "大宅",
                "等",
                "景点",
                "吸引",
                "了",
                "众多",
                "游客",
                "。",
            ],
            questions: [
                {
                    questionName: "七年级-第一单元-第15题",
                    question: " The movie title mentioned above?",
                    questionAnswer:
                        "A. Singapore'sMarinaBaySands. B. Malaysia'sheritageCheongFattSzeMansion. C. CrazyRichAsians D. Singapore",
                    correctAnswer: "C",
                    wrongAnswer: "B",
                    note: "答案中的四个单词都在文中出现了，请注意问题是说电影的名称，所以学生应当注意问题的对象是电影的名称。",
                },
                {
                    questionName: "七年级-第一单元-第16题",
                    question: " Where is the filming location for the movie?",
                    questionAnswer:
                        "A. Singapore. B. Malaysia. C. Singapore And Malaysia D. China",
                    correctAnswer: "C",
                    wrongAnswer: "A/B",
                    note: "问题是电影拍摄的地点是那里，电影拍摄的地点是新加坡和马来西亚，所以单独的说说新加坡和马来西亚都不是在合适的答案。",
                },
            ],
            isLoading: false, // 加载状态，默认为 false
            isLoadingReSet: false, // 重置错题，默认为 false
            isLoadingCancleSet: false, // 取消设置错题，默认为 false
            isLoadingEndSet: false, // 设置结束位置，默认为 false
            isLoadingStartSet: false, // 设置结束位置，默认为 false
            speed: this.initialSpeed,
            isShowSpeedSettingFlag: false,
        };
    },
    methods: {
        handleStartPlayer() {
            this.$message.success("开始播放");
        },
        handleStopPlayer() {
            this.$message.success("停止播放");
        },
        handleSetSpeed() {
            this.isShowSpeedSettingFlag = true;
        },
        handleSpeedSet(speed) {
            this.speed = speed;
            this.isShowSpeedSettingFlag = false;
            this.$message({
                type: "success",
                message: `全局播放速度已设置为 ${this.speed}x`,
            });
        },
        handleStartCheckPlay() {
            if (this.selectedAnchors.length === 0) {
                this.$message.warning("请先选择至少一道错题");
                return;
            }
            // 如果有选中的错题，可以继续后续的播放逻辑
            this.$message.success("开始播放选中的错题");
            //   // 示例：播放第一个选中的错题
            //   const firstSelectedAnchorIndex = this.selectedAnchors[0];
            //   this.seekToAnchor(firstSelectedAnchorIndex);
        },
        handleStartToEndPlay() {
            this.$message.success("从头开始播放。");
        },
        /**
         * 提取题号
         * @param {string} questionName - 题目名称，例如 "七年级-第一单元-第15题"
         * @returns {string} 提取的题号，例如 "第15题"
         */
        extractQuestionNumber(questionName) {
            // 使用正则表达式匹配 "第XX题"
            const match = questionName.match(/第(\d+)题/);
            if (match) {
                return `第${match[1]}题`;
            }
            return questionName; // 如果没有匹配到，返回原始字符串
        },
        /**
         * 设置开始位置
         */
        handlesetStartLocation() {
            //
        },
        /**
         * 设置结束位置
         */
        handlesetEndLocation() {
            // Pause audio logic
        },
        /**
         * 取消设置
         */
        cancleSet() {
            // Restart audio logic
            this.currentTime = 0;
            this.highlightedText = [];
        },
        /**
         * 重新设置
         */
        reSet() {
            this.isLoadingReSet = true; // 开始加载
            setTimeout(() => {
                this.isLoadingReSet = false; // 结束加载
                this.$message.success("重置错题成功。");
                this.anchors = [];
            }, 2000); // 模拟3秒上传时间
        },
        selectAnchor() {
            // Select anchor logic
        },
        seekToAnchor(index) {
            // Seek to anchor logic
            const anchorTime = this.anchors[index];
            this.currentTime = anchorTime;
            this.updateCurrentTime({ target: { value: anchorTime } });
        },
        updateCurrentTime(event) {
            // Update current time logic
            console.log("Current time:", event.target.value);
            this.currentTime = event.target.value;
            this.highlightTextAt(this.currentTime);
        },
        highlightTextAt(time) {
            // Highlight text at current time logic
            this.highlightedText = [];
            const wordsPerSecondOriginal = this.originalText.length / 1350;
            const wordsPerSecondTranslation = this.translationText.length / 1350;

            const indexToHighlightOriginal = Math.floor(
                time * wordsPerSecondOriginal
            );
            const indexToHighlightTranslation = Math.floor(
                time * wordsPerSecondTranslation
            );

            for (let i = 0; i <= indexToHighlightOriginal; i++) {
                this.highlightedText.push(i);
            }

            for (let i = 0; i <= indexToHighlightTranslation; i++) {
                this.highlightedText.push(i + this.originalText.length); // 偏移量为原文长度
            }
        },
        toggleAnchor(index) {
            console.log("toggleAnchor", index);
            console.log("toggleAnchor", this.selectedAnchors);
            // Toggle anchor selection
            const indexToToggle = this.selectedAnchors.indexOf(index);
            console.log("toggleAnchor", indexToToggle);
            if (indexToToggle > -1) {
                this.selectedAnchors.splice(indexToToggle, 1);
            } else {
                this.selectedAnchors.push(index);
                console.log("toggleAnchor", this.selectedAnchors);
            }
        },
        seekToTime(event) {
            const timeInSeconds = event.target.value;
            this.currentTime = timeInSeconds;
            this.audio.currentTime = this.currentTime;
            this.play();
        },
        back() {
            // 例如，可以关闭示例文件视图
            this.$emit("close-play-file");
        },
        getAnchorLabel(index) {
            // 根据索引生成标签
            const pairIndex = Math.floor(index / 2) + 1; // 计算是第几对
            const label = index % 2 === 0 ? "s" : "e"; // 偶数索引为 's'，奇数索引为 'e'
            return `${pairIndex}_${label}`;
        },
        /**
         * 提交设置错题
         */
        submit() {
            this.isLoading = true; // 开始加载
            setTimeout(() => {
                this.isLoading = false; // 结束加载
                this.$message.success("生成错题集成功");
                this.$emit("submit-creat-wrong-file"); // 触发父组件的事件
            }, 3000); // 模拟3秒上传时间
        },
    },
};
</script>

<style scoped>
.audio-player {
    border: 1px solid #ccc;
    padding: 20px;
    width: 1500px;
    /* Adjust width as needed */
    height: 830px;
    margin: 0 auto;
}

.tabs {
    display: flex;
    margin-bottom: 20px;
}

.tabs button {
    flex: 1;
    padding: 10px;
    border: none;
    background-color: #f0f0f0;
    cursor: pointer;
}

.tabs .active {
    background-color: #666;
    color: white;
}

.audio-control {
    margin-bottom: 30px;
    /* Add more margin-bottom to move content down *
  
  }
  
  .audio-control.title {
      text-align: center;
      /* 将标题居中 */
    margin-bottom: 30px;
}

.audio-progress {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    position: relative;
    width: 100%;
    height: 40px;
    /* Make progress bar larger */
}

.audio-progress .time {
    margin: 0 10px;
}

.audio-anchors {
    display: flex;
    flex-direction: column;
    /* margin-bottom: 20px; */
    /* Add more margin-bottom to move content down */
    background: #ccc;
    margin-top: -15px;
}

.anchor-checkboxes {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    /* Add space between checkboxes */
}

.anchor-checkboxes input[type="checkbox"] {
    margin-right: 5px;
}

.text-content {
    margin-top: -30px;
    /* Add more margin-bottom to move content down */
    overflow-x: hidden;
    /* Hide horizontal scrollbar */
    overflow-y: auto;
    /* Show vertical scrollbar when needed/
      max-height: 400px; / Set a maximum height /
      padding-right: 10px; / Add padding to avoid content from being hidden by scrollbar */
    background: #45a049;
}

.text-original,
.text-translation {
    /* margin-bottom: 10px; */
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 5;
    /* Number of lines to show */
    -webkit-box-orient: vertical;
}

.text-original p span.highlighted,
.text-translation p span.highlighted {
    color: red;
}

.text-original p span,
.text-translation p span {
    display: inline-block;
    /* Make each word an inline-block element */
    margin-right: 2px;
    /* Add space between words */
}

.text-original p span.highlighted,
.text-translation p span.highlighted {
    color: red;
}

.playback-controls {
    display: flex;
    /* justify-content: space-between; */
    margin-bottom: 20px;
}

.playback-controls button {
    padding: 10px 20px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    margin-right: 30px;
}

.playback-controls button:hover {
    background-color: #45a049;
}

input[type="range"] {
    flex: 1;
    height: 20px;
    /* Make the slider thicker */
    cursor: pointer;
}

.anchor {
    position: absolute;
    top: -5px;
    /* Move anchor up by 5px /
      left: 0;
      transform: translateX(-50%);
      width: 10px;
      height: 10px;
      background-color: transparent;
      margin-left: -5px; / Center the anchor point */
}

.anchor-arrow {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 0;
    height: 0;
    border-left: 5px solid transparent;
    border-right: 5px solid transparent;
    border-top: 5px solid #4caf50;
    display: flex;
    align-items: center;
    justify-content: center;
}

.anchor-number {
    position: relative;
    top: -12px;
    color: red;
    font-size: 12px;
}

.anchor-line {
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 2px;
    height: 20px;
    /* Make the line longer */
    background-color: #4caf50;
    z-index: 1;
}

.return-button {
    float: right;
    /* 将按钮浮动到右侧 */
    background-color: #4caf50;
    /* 按钮背景颜色 */
    border: none;
    /* 去掉边框 */
    padding: 5px 10px;
    /* 添加内边距 */
    cursor: pointer;
    /* 鼠标悬停时显示手型 */
    font-size: 14px;
    /* 字体大小 */
    border-radius: 5px;
    color: #fff;
    width: 100px;
    margin-top: -50px;
    margin-bottom: 20px;
}

.return-button:hover {
    background-color: #4caf50;
    /* 鼠标悬停时的背景颜色 */
}

.questions {
    background-color: #f0f0f0;
    padding: 10px;
    border-radius: 5px;
    overflow-x: hidden;
    overflow-y: auto;
    max-height: 270px;
    /* Set a maximum height */
}

.questions p {
    margin: 5px 0;
}

.questions hr {
    border: none;
    border-top: 1px solid #4caf50;
    /* margin: 10px 0; */
}
</style>
